﻿using System;
using System.Configuration;
using Castle.Core.Logging;
using log4net;
using log4net.Config;
using Sail.Environment;

namespace Sail.Logging
{
    public class SailLog4netFactory : AbstractLoggerFactory
    {
        private static bool _isFileWatched = false;

        public SailLog4netFactory(IHostEnvironment hostEnvironment)
            : this(ConfigurationManager.AppSettings["log4net.Config"], hostEnvironment) { }

        public SailLog4netFactory(string configFilename, IHostEnvironment hostEnvironment)
        {
            if (!_isFileWatched && !string.IsNullOrWhiteSpace(configFilename) && hostEnvironment.IsFullTrust)
            {
                XmlConfigurator.ConfigureAndWatch(GetConfigFile(configFilename));
                _isFileWatched = true;
            }
        }

        public override Castle.Core.Logging.ILogger Create(string name, LoggerLevel level)
        {
            throw new NotSupportedException("日志无法创建.请检查配置文件");
        }

        public override Castle.Core.Logging.ILogger Create(string name)
        {
            return new SailLog4netLogger(LogManager.GetLogger(name), this);
        }
    }
}
